var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};

function send404(res){
    res.writeHead(404,{"Content-Type":"text/plain"});
    res.end("Error 404: The files you request is gone.");
}

function sendFile(res,filePath,fileContents){
    res.writeHead(200,{"Content-Type":mime.lookup(path.basename(filePath))});
    res.end(fileContents);
}

function serveStatic(res,cache,absPath){
    if(cache[absPath]){
        sendFile(res,absPath,cache[absPath]);
    }else {
        fs.exists(absPath,function(exist){
            if(exist){
                fs.readFile(absPath,function(err,content){
                    if(err){
                        send404(res);
                    }else {
                        cache[absPath] = content;
                        sendFile(res,absPath,content);
                    }
                });
            }else {
                send404(res);
            }
        });
    }
}

var server = http.createServer(function(req,res){
    var filePath = false;
    if(req.url == "/"){
        filePath = "public/index.html";
    }else {
        filePath = "public" + req.url;
    }
    var absPath = "./" + filePath;
    serveStatic(res,cache,absPath);
});

server.listen(8899);

var chatServer = require("./lib/chat_server");
chatServer.listen(server);